package priv.bestbeat.cloud.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.impl.PublicClaims;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import priv.bestbeat.cloud.common.configuration.JWTConfiguration;
import priv.bestbeat.cloud.common.create.JWTCRT;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.UUID;

/**
 * jwt 工具
 * @author 张渠钦
 * @date 2021/8/10 17:32
 */
public final class JWTUtil {

    /**
     *  校验颁发者和有效时间
     * @param jwt
     * @return
     */
    public static boolean basicValid(String jwt) {
        DecodedJWT decodedJWT = JWT.decode(jwt);
        Claim issuerClaim = decodedJWT.getClaim(PublicClaims.ISSUER);
        if (!JWTConfiguration.getIssuer().equals(issuerClaim.asString())) {
            return false;
        }
        Claim expiresAtClaim = decodedJWT.getClaim(PublicClaims.EXPIRES_AT);
        return expiresAtClaim.asDate().after(new Date());
    }

    /**
     * 创建JWT
     * @param jwtcrt
     * @return
     */
    public static String create(JWTCRT jwtcrt) {
        // 颁布时间
        LocalDateTime now = LocalDateTime.now();
        Instant instant = now.atZone(ZoneId.systemDefault()).toInstant();
        Date issuedAt = Date.from(instant);

        // 过期时间
        now = now.plusMinutes(JWTConfiguration.getExpiresMinutes());
        instant = now.atZone(ZoneId.systemDefault()).toInstant();
        Date expiresAt = Date.from(instant);

        // 分布式环境下全局唯一，不需要有序
        String uuid = UUID.randomUUID().toString();
        String token = JWT.create()
                // 颁发者
                .withIssuer(JWTConfiguration.getIssuer())
                // 验证适用的来源对象
                // 用户名/ip地址
                .withAudience(jwtcrt.getAudiences())
                // 所有者
                .withSubject("user-"+jwtcrt.getUsername())
                // 颁布时间
                .withIssuedAt(issuedAt)
                // 过期时间
                .withExpiresAt(expiresAt)
                // token ID 便于服务端侧失效token
                .withJWTId(uuid)
                .sign(JWTConfiguration.getAlgorithm());
        return token;
    }

}
